import {getHttp, responseText} from 'cess-core';
import {jest} from 'jest-lite'


var http = undefined;
//因为浏览器中有 fetch 函数，会阻止 ajax 函数执行，所以先要把 fetch 函数置 null，为了不影响其他测试，在测试完成后要把 fetch 还原
var originFetch = window.fetch;
describe('browser ajax', function() {

    beforeEach(() => {
        http = getHttp("ajax 2" + new Date().getTime() + "" +Math.random());
        window.fetch = null;
    });

    afterEach(()=>{
        window.fetch = originFetch;
    })

    //测试 http 普通请求
    //返回普通字符串，appliction/text
    it('ajax request', async ()=>{

        const spyFn = jest.spyOn(XMLHttpRequest.prototype,'send')

        var urlPath = 'http://localhost:3001/api/request';

        var str = await http({
            url: urlPath
        })

        //确保是执行的 ajax 请求
        expect(spyFn).toHaveBeenCalled();
        expect(spyFn).toHaveBeenCalledTimes(1);

        //检验返回结果
        str.text = await responseText(str);
        expect('ok').toBe(str.text)
        expect(200).toBe(str.status)
        expect('OK').toBe(str.statusText)

    })

    //测试 http 请求返回 json 数据
    it("ajax json", async ()=>{

        const spyFn = jest.spyOn(XMLHttpRequest.prototype,'send')

        var httpJsonTest = async (url, data)=>{
            spyFn.mockClear();
            //发起请求
            var obj = await http({
                url: url,
            })
            //确保是执行的 ajax 请求
            expect(spyFn).toHaveBeenCalled();

            expect(spyFn).toHaveBeenCalledTimes(1);
            //检验返回结果
            expect(obj).toStrictEqual(data)
        }

        await httpJsonTest('http://localhost:3001/api/json/str', 'ok')
        await httpJsonTest('http://localhost:3001/api/json/obj', {
            name: 'name1',
            value: 'value1',
        })
        await httpJsonTest('http://localhost:3001/api/json/number', 10)
        await httpJsonTest('http://localhost:3001/api/json/str_array',
          ['one','two','thee'])
        await httpJsonTest('http://localhost:3001/api/json/obj_array',
          [{name:'one'},{name:'two'},{name:'thee'}])

    })

});
